package com.ray.test.actuator.spring;

import com.alibaba.fastjson.JSON;
import com.ray.test.actuator.Actuator;
import com.ray.test.actuator.ActuatorResult;
import com.ray.test.actuator.MethodParams;
import com.ray.test.actuator.params.ParamsBuilder;
import com.ray.test.exception.TestException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StopWatch;

import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.List;

/**
 * @author bo shen
 * @Description: 容器对象类执行器
 * @Class: ClassSpringActuator
 * @Package com.ray.test.actuator.spring
 * @date 2019/12/12 13:56
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class InterfaceSpringActuator implements Actuator{
    @Override
    public ActuatorResult doActuator(MethodParams methodParams) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        log.info("当前执行类:[{}]-方法[{}]的单元测试.",methodParams.getTargetClassName(),methodParams.getMethodName());
        if(!methodParams.getTargetClass().isInterface()){
            throw new TestException(String.format("%s不是可执行的类",methodParams.getTargetClassName()));
        }
        //构建参数
        Parameter[] parameters = methodParams.getMethod().getParameters();
        log.info("方法参数数量:{},类型为:{}",parameters.length, Arrays.toString(parameters));
        List<Object> params = ParamsBuilder.getInstance().bulider(parameters,methodParams.getMethod(),null);
        //方法执行
        try {
            log.info("执行参数:{}", JSON.toJSONString(params));
             methodParams.getMethod().invoke(methodParams.getBean(), params.toArray());
        }catch (Exception e){
            log.info("当前执行类:[{}]-方法[{}]的单元测试-失败",methodParams.getTargetClassName(),methodParams.getMethodName(),e);
            return new ActuatorResult(false,e.getMessage());
        }
        stopWatch.stop();
        log.info("当前执行类:[{}]-方法[{}]的单元测试-成功，耗时:{}",methodParams.getTargetClassName(),methodParams.getMethodName(),stopWatch.getTotalTimeMillis());
        return new ActuatorResult(true,"执行成功");
    }
}
